package com.free.framework.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.free.framework.mvp.BaseMvpPresenter;
import com.free.framework.mvp.IBaseMvpView;
import com.free.framework.widgets.custom_loading.LoadingUtils;

/**
 * @author 李博
 * @date 16/10/24
 * @desc BaseFragment
 */
public abstract class BaseFragment<P extends BaseMvpPresenter> extends Fragment implements IBaseMvpView {

    private FragmentActivity mFragAct;

    protected P mPresenter;

    protected View rootView;

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
        mFragAct = (FragmentActivity) activity;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = createPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater,container,savedInstanceState);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(rootView==null){
            rootView = view;
            if (null != mPresenter) {
                mPresenter.attachView(this);
                onPresenterCreated();
            }
        }
    }


    protected abstract P createPresenter();

//    protected P createPresenter() {
//        return null;
//    }

    /**
     * @desc Presenter创建完成的回调
     */
    protected void onPresenterCreated() {}


    @Override
    public void showToast(String toast) {
        if (!TextUtils.isEmpty(toast)) {
            Toast.makeText(mFragAct, toast, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showLoadingView(boolean cancelable) {
        if(cancelable){
            FragmentManager fragmentManager = getFragmentManager();
            if(fragmentManager!=null){
                LoadingUtils.showDialog(fragmentManager);
            }
        }
    }

    @Override
    public void hideLoadingView() {
        FragmentManager fragmentManager = getFragmentManager();
        if(fragmentManager!=null){
            LoadingUtils.dismiss(fragmentManager);
        }
    }

    @Override
    public void hideRefreshingView() {

    }

    @Override
    public void showSSLError() {

    }

    /**
     * @desc 防止Activity被回收导致getActivity == null的情况
     * @return
     */
    public FragmentActivity getHostActivity() {
        FragmentActivity hostAct = super.getActivity();
        return null == hostAct ? mFragAct : hostAct;
    }

    public void hideInputMethod(View v) {
        try {
            InputMethodManager imm = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    private ProgressDialog mProgressDialog;

    public ProgressDialog createProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setCancelable(true);
            mProgressDialog
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            destroyProgressDialog();
                        }
                    });
        }

        if (!mProgressDialog.isShowing() && !getActivity().isFinishing()) {
            mProgressDialog.show();
        }

        return mProgressDialog;
    }

    public void destroyProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter!=null && mPresenter.isViewAttached()) {
            mPresenter.detachView(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mPresenter!=null) {
            mPresenter.destroy();
            mPresenter = null;
        }
    }


    protected final <E extends View> E getView(int id) {
        try {
            return (E) rootView.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e(getClass().getName(), "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

}
